package com.test38_集合.util;

import java.util.Iterator;

public class LinkImpl<T> implements ILink<T> {
    private class Node {
        private T data;     // 节点数据
        private Node next;  // 保存下一个节点

        public Node(T data) {
            this.data = data;
        }
    }
    // ------------ 编写链表实现类 ------------
    private Node root;
    private Node last;
    private Node currentNode;

    @Override
    public void add(T e) {
        Node newNode = new Node(e);
        if (this.root == null) {
            this.root = newNode;
        } else {
            this.last.next = newNode;
        }
        this.last = newNode;
    }

    @Override
    public Iterator<T> iterator() {
        this.currentNode = this.root;
        return new LinkIter();
    }

    private class LinkIter implements Iterator<T> {
        @Override
        public boolean hasNext() {
            return LinkImpl.this.currentNode != null;
        }

        @Override
        public T next() {
            T data = LinkImpl.this.currentNode.data;    // 获取节点数据
            LinkImpl.this.currentNode = LinkImpl.this.currentNode.next; // 修改当前节点
            return data;
        }
    }
}
